package cn.uway.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SignatureUtils {
	
	protected static  Logger log = LoggerFactory.getLogger(SignatureUtils.class);
	
	public static  Map<String,String> appKeyMap = new HashMap<String,String>();
    static{
    	appKeyMap.put("71bdd2fe3ede4716a409b76b998f8dc2", "5c624e9a73f54544b4ff3e3fafc34fa2"); //app
    	appKeyMap.put("67d307e4d1d143d6acd6a33a87d367b9", "55f2bfde6cd64f00acd2294bbd0963f4"); //web
    }
    
    public static Map<String,String>  getSignParameters(HttpServletRequest request){
		return appKeyMap;
    	
    }
    
    /**
     * 验证数字签名
     * @param request
     * @return
     */
    public static Map<String,String>  checkSignature(HttpServletRequest request){
    	Map<String, String> resultMap = new HashMap<String, String>();    		
		Map<String, String[]> paraMap = request.getParameterMap();
		if(paraMap == null || paraMap.size() == 0) {
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
			resultMap.put(PubValue.RET_MSG_KEY, "请求参数不能为空");
			return resultMap;
		}	
		String appId = request.getParameter("appId");
		if(WebUtils.isEmpty(appId)){
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
			resultMap.put(PubValue.RET_MSG_KEY, "参数[appId]不能为空");
			return resultMap;
		}		
		String sign = request.getParameter("sign");
		if(WebUtils.isEmpty(sign)){
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
			resultMap.put(PubValue.RET_MSG_KEY, "参数[sign]不能为空");
			return resultMap;
		}
		String secretKey = appKeyMap.get(appId);
		if(secretKey==null){
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
			resultMap.put(PubValue.RET_MSG_KEY, "参数[appId]无效");
			return resultMap;
		}
		//按照参数的key值从A-Z排序，keyvalue拼接，sign和空的key不参与拼接
		Map<String, String> paramTreeMap = new TreeMap<String, String>();
		for( Entry<String, String[]> entry : paraMap.entrySet() ) {
			String key = entry.getKey();
			String[] value = entry.getValue();	
			if(WebUtils.isNotEmpty(key) && !"null".equals(key) && !"sign".equals(key)){ //参数sign不参与数字签名
				if( value != null && value.length == 1) {
					String val = value[0];
					if(val!=null && !"".equals(val.trim())){
						paramTreeMap.put(key, val);
					}					
				} 
			}			
		}
		log.debug("===============paramTreeMap={}",paramTreeMap);
		//计算数字签名字符串
		String computeSign = getSignString(secretKey, paramTreeMap);
		log.debug("===============computeSign={}, request.param.sign={}", computeSign, sign);
		if(!computeSign.equals(sign)){
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
			resultMap.put(PubValue.RET_MSG_KEY, "数字签名验证未通过");
			return resultMap;
		}
		else{
			resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_SUCCESS);
			resultMap.put(PubValue.RET_MSG_KEY, "验证通过");
			return resultMap;
		}
    }
    
    private  static String  getSignString(String secretKey, Map<String, String> paramTreeMap){
    	StringBuilder sb = new StringBuilder();
    	Iterator<String> iter = paramTreeMap.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			sb.append(name).append(paramTreeMap.get(name));
		}
		sb.append(secretKey);
		return MD5Encoder.encode(sb.toString());
    }
       
    
    public static void main(String[] args) {
		System.out.println(WebUtils.createUUID());
	}
       
	
}
